﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;

namespace WhsFacebook.Net.Web.Database
{
    partial class WhsFacebookEntities
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(WhsFacebookEntities));

        public void EnsureWhsTowerImage(string manu, string model, Image img, bool forceUpdate)
        {
            if (string.IsNullOrEmpty(manu))
                throw new ArgumentException("null or empty", "manu");

            if (string.IsNullOrEmpty(model))
                throw new ArgumentException("null or empty", "model");

            if (img == null)
                throw new ArgumentNullException("img");

            try
            {
                // tower image does exist?
                var ti = this.WhsTowerImages.Where(o => o.SystemManufacturer == manu && o.SystemModel == model).FirstOrDefault();

                if (ti == null)
                {
                    AddToWhsTowerImages(new DbWhsTowerImage()
                    {
                        SystemManufacturer = manu,
                        SystemModel = model,
                        TowerJpeg = img.ToByteArrayJpeg()
                    });

                    SaveChanges();
                }
                else if (forceUpdate)
                {
                    ti.TowerJpeg = img.ToByteArrayJpeg();

                    SaveChanges();
                }
            }
            catch (Exception x)
            {
                _log.Error("Failed to ensure WHS tower image for model/manufacturer", x);

                throw;
            }
        }

        public void EnsureWhsTowerImage(Guid instanceId, Image img, bool forceUpdate)
        {
            if (instanceId == Guid.Empty)
                throw new ArgumentException("instanceId is invalid/empty", "instanceId");

            if (img == null)
                throw new ArgumentNullException("img");

            try
            {
                // tower image does exist?
                var ti = this.WhsTowerImages.Where(o => o.InstanceId == instanceId).FirstOrDefault();

                if (ti == null)
                {
                    AddToWhsTowerImages(new DbWhsTowerImage()
                    {
                        InstanceId = instanceId,
                        TowerJpeg = img.ToByteArrayJpeg()
                    });

                    SaveChanges();
                }
                else if (forceUpdate)
                {
                    ti.TowerJpeg = img.ToByteArrayJpeg();

                    SaveChanges();
                }
            }
            catch (Exception x)
            {
                _log.Error("Failed to ensure WHS tower image for instance " + instanceId, x);

                throw;
            }
        }
    }
}